﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Runtime.InteropServices;
using System.Reflection;

namespace OutlookMailClassifier.Tests
{
    public class Helper
    {
        private Outlook.Application application = null;

        // Source: http://msdn.microsoft.com/en-us/library/ff462097.aspx
        /// <summary>
        /// Return the Outlook.Application object of a running or started Outlook session
        /// </summary>
        public Outlook.Application GetApplicationObject()
        {
            if (application == null)
            {
                // Check whether there is an Outlook process running.
                if (System.Diagnostics.Process.GetProcessesByName("OUTLOOK").Count() > 0)
                {
                    // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                    application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
                }
                else
                {
                    // If not, create a new instance of Outlook and log on to the default profile.
                    // application = new Outlook.Application();
                    // Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
                    // nameSpace.Logon("", "", Missing.Value, Missing.Value);
                    throw new System.InvalidOperationException("Outlook must be started prior to starting the unit tests.");
                }
            }

            // Return the Outlook Application object.
            return application;
        }

        /// <summary>
        /// Load a .pst file as Outlook store into Outlook given its filename
        /// </summary>
        public void LoadPstByPath(String path)
        {
            GetApplicationObject().GetNamespace("MAPI").AddStoreEx(System.IO.Path.GetFullPath(path), Outlook.OlStoreType.olStoreUnicode);
        }

        /// <summary>
        /// Remove a .pst file as Outlook store from Outlook given the path to the .pst file
        /// </summary>
        // http://msdn.microsoft.com/de-ch/library/bb612380.aspx
        public void UnloadPstByPath(String path)
        {
            path = System.IO.Path.GetFullPath(path);
            Outlook.Stores stores = GetApplicationObject().Session.Stores;
            foreach (Outlook.Store store in stores)
            {
                if (store.FilePath == path)
                {
                    Outlook.Folder folder = store.GetRootFolder() as Outlook.Folder;
                    GetApplicationObject().Session.RemoveStore(folder);
                }
            }
        }

    }
}
